﻿using System;
using System.Web.Mvc;
using LY.Entity.Entities;
using LY.Interface;
using QJ.CMS.Filters;
using LY.Entity.SearchEntity;
using LY.Entity.PageSearch;
using LY.Entity;
using LY.Entity.Jsons;


using System.Text;
using LY.Extension;

namespace QJ.CMS.Controllers
{
    [MyAuthorization]
    public class UserProjectController : MyControllerBase
    {
        // GET: /UserProject/
        private IProjectService _pro;
        private IProjectAttentionService _proatt;
        private IProjectItemService _item;
        private IMemberService _member;
        public UserProjectController(IProjectService pro, IProjectAttentionService proatt, IProjectItemService item, IMemberService member)
        {
            _pro = pro;
            _proatt = proatt;
            _item = item;
            _member = member;
        }
        #region 我发起的项目
        /// <summary>
        /// 我发起的项目
        /// </summary>
        /// <returns></returns>
        public ActionResult MyProject()
        {
            return View();
        }
        [HttpPost]
        public JsonResult MyProject(ProjectSearch search, FormCollection form)
        {
            string auditStatus = Request["AuditStatus"];
            if (auditStatus != "")
            {
                search.AuditStatus = auditStatus;
            }
            PageView view = new PageView(form);
            //string colkey = form["colkey"];
            //string colsinfo = form["colsinfo"];
            var member = (U_Member)Session["CurrentUser"];
            search.MemberId = member.ID;
            PagedList<ProjectEx> bList = _pro.QueryProjectMyProject(search, view);
            foreach (var item in bList.DataList)
            {
                item.ProjectStatusName = GetUserProjectStatusName((int)item.AuditStatus);
                // if (item.ProjectStatus == 0 || item.ProjectStatus == 101 || item.ProjectStatus == 3)

                //210 项目未发布成功
                if (item.AuditStatus != 210)
                {
                    var bj = new StringBuilder();
                    bj.Append("<p><a class=\"b-l-btn\"  href=\"/Default/Detail/" + item.Id + "\" target=\"_blank\">项目预览</a></p>");
                    bj.Append("<p><a class=\"b-l-btn\"  href=\"/Project/AddProject/" + item.Id + "\">项目编辑</a></p>");
                    bj.Append("<p><a class=\"b-l-btn\" style='cursor: pointer' onclick=\"deleteProject(" + "'" + item.Id + "'" + ")\">删除</a></p>");
                    //bj.Append("<p><a class=\"b-l-btn\"  href=\"/UserProject/ProjectDatelinetree?pid=" + item.Id + "\">项目时间轴</a></p>");
                    // bj.Append("<p><a class=\"b-l-btn\"  href=\"/UserProject/QuestionManagement/" + item.Id + "\">问题管理</a></p>");
                    item.BianJi = bj.ToString();
                }
                else
                {
                    var bj = new StringBuilder();
                    bj.Append("<p><a class=\"b-l-btn\"  href=\"/Default/Detail/" + item.Id + "\" target=\"_blank\">项目预览</a></p>");
                    bj.Append("<p><a class=\"b-l-btn\"  href=\"/UserProject/ProjectDatelinetree?pid=" + item.Id + "\">项目时间轴</a></p>");
                    bj.Append("<p><a class=\"b-l-btn\"  href=\"/UserProject/QuestionManagement/" + item.Id + "\">问题管理</a></p>");
                    bj.Append("<p><a class=\"b-l-btn\"  href=\"/UserProject/SupporterList/" + item.Id + "\">支持人列表</a></p>");
                    item.BianJi = bj.ToString();
                }
            }

            //Response.Clear();
            return Json(bList);
        }


        public static string GetUserProjectStatusName(int AuditStatus)
        {
            var sb = new StringBuilder();
            if (AuditStatus == 0)
            {
                sb.Append("还未发布");
            }
            else if (AuditStatus < 210 && AuditStatus > 109)
            {
                sb.Append("项目审核中");
            }
            else if (AuditStatus == 109)
            {
                sb.Append("审核不通过");
            }
            else if (AuditStatus == 210)
            {
                sb.Append("众筹中");
            }
            else if (AuditStatus == 220)
            {
                sb.Append("众筹成功");
            }
            else if (AuditStatus == 219)
            {
                sb.Append("众筹失败");
            }
            return sb.ToString();
        }

        public ActionResult SupporterList(string id)
        {
            ViewBag.ID = id;
            return View();
        }
        [HttpPost]
        public ActionResult SupporterList(FormCollection form, string id)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];
            PagedList<U_Member_EX> rList = _pro.QueryInvestmentMemberList(view, int.Parse(id));
            JsonQTable at = JsonQTable.ConvertFromPagedList<U_Member_EX>(rList, colkey, colsinfo.Split(','));
            return Json(at);
        }

        //问题管理
        public ActionResult QuestionManagement()
        {
            return View();
        }
        [HttpPost]
        public ActionResult QuestionManagement(FormCollection form, string id)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];
            PagedList<R_ProjectQuestion_EX> rList = _pro.QuestionManagement(view, id);
            JsonQTable at = JsonQTable.ConvertFromPagedList<R_ProjectQuestion_EX>(rList, colkey, colsinfo.Split(','));
            return Json(at);
        }


        //问题详细列表
        [HttpPost]
        public ActionResult QuestionList(string id, string mid)
        {
            return Json(_pro.GetQuestionList(id, mid));
        }
        //问题回复
        [HttpPost]
        public ActionResult ReplyQuestion(string rid, string pid, string mid, string rmid, string content)
        {
            JsonSMsg msg = new JsonSMsg();

            R_ProjectQuestion_EX pq = new R_ProjectQuestion_EX();
            pq.ReplyId = _pro.GetQIdByMemberId(mid, 1);
            pq.Message = content;
            pq.ProjectId = int.Parse(pid);
            pq.MemberId = int.Parse(mid);
            pq.RMemberId = int.Parse(rmid);
            pq.CreateTime = DateTime.Now;

            int result = _pro.ReplyQuestion(pq);

            if (result > 0)
            {
                msg.Status = 1;
                msg.Message = "回复成功！";
                msg.Data = Url.Action("QuestionManagement", new { id = pq.ProjectId });
            }
            else
            {
                msg.Status = -1;
                msg.Message = "回复失败";
            }

            return Json(msg);
        }

        //采纳问题
        /*[HttpPost]
        public ActionResult AdoptQuestion(string id)
        {
            JsonSMsg msg = new JsonSMsg();

            int result = _pro.AdoptQuestion(id);

            if (result > 0)
            {
                msg.Status = 1;
                msg.Message = "采纳成功！";
                msg.Data = Url.Action("QuestionManagement");
            }
            else
            {
                msg.Status = -1;
                msg.Message = "采纳失败！";
            }

            return Json(msg);
        }*/

        //删除问题及回复
        [HttpPost]
        public ActionResult DeleteQuestion(string mid, string pid)
        {
            JsonSMsg msg = new JsonSMsg();

            int result = _pro.DeleteQuestion(mid, pid);

            if (result > 0)
            {
                msg.Status = 1;
                msg.Message = "删除成功！";
                msg.Data = Url.Action("QuestionManagement", new { id = pid });
            }
            else
            {
                msg.Status = -1;
                msg.Message = "删除失败！";
            }

            return Json(msg);
        }
        #endregion

        #region 我支持的项目
        /// <summary>
        /// 我支持的项目
        /// </summary>
        /// <returns></returns>
        public ActionResult SecondProject()
        {
            return View();
        }

        [HttpPost]
        public ActionResult SecondProject(ProjectSearch search, FormCollection form)
        {
            string paystatus = Request["PayStatus"];
            if (paystatus != "")
            {
                search.PayStatus = paystatus;
            }
            PageView view = new PageView(form);
            var member = (U_Member)Session["CurrentUser"];
            search.MemberId = member.ID;
            PagedList<ProjectEx> bList = _pro.QueryBoughtProject(search, view);

            foreach (var item in bList.DataList)
            {
                //未支付||//付款失败
                if (item.PayStatus == 0 || item.PayStatus == 2)
                {
                    var bj = new StringBuilder();
                    bj.Append("<p><a class=\"btn\" style=\"padding-left:13px;\" target=\"_blank\" href=\"/UserOrder/OrderConfirm?serialNumber=" + item.SerialNumber + "\">立即支付</a></p>");
                    bj.Append("<p><a class=\"b-l-btn\" target=\"_blank\" href=\"/UserOrder/OrderDetail?SerialNumber=" + item.SerialNumber + "\">交易详情</a></p>");
                    bj.Append("<p><a class=\"b-l-btn\" style=\"cursor: pointer\" onclick=\"cancelOrder(" + "'" + item.SerialNumber + "'" + ")\">取消订单</a></p>");
                    item.BianJi = bj.ToString();
                }
                //已支付
                else if (item.PayStatus == 1)
                {
                    var bj = new StringBuilder();
                    bj.Append("<p><a class=\"b-l-btn\" target=\"_blank\"  href=\"/UserOrder/OrderDetail?SerialNumber=" + item.SerialNumber + "\">申请退款</a></p>");
                    //项目成功，确认收货
                    if (item.AuditStatus == 220)
                    {
                        bj.Append("<p><a class=\"b-l-btn\" style='cursor: pointer' href=\"/UserProject/ConfirmOrder/" + item.SerialNumber + "\">确认收货</a></p>");
                    }
                    item.BianJi = bj.ToString();
                }
                //交易关闭
                else if (item.PayStatus == 10)
                {
                    var bj = new StringBuilder();
                    bj.Append("<p><a class=\"b-l-btn\" target=\"_blank\" href=\"/UserOrder/OrderDetail?SerialNumber=" + item.SerialNumber + "\">交易详情</a></p>");
                    bj.Append("<p><a class=\"b-l-btn\" style='cursor: pointer' onclick=\"deleteOrder(" + "'" + item.SerialNumber + "'" + ")\">删除</a></p>");
                    item.BianJi = bj.ToString();
                }
                //已收货
                else if (item.PayStatus == 9)
                {
                    var bj = new StringBuilder();
                    bj.Append("<p><a class=\"b-l-btn\" target=\"_blank\" href=\"/UserOrder/OrderDetail?SerialNumber=" + item.SerialNumber + "\">交易详情</a></p>");
                    bj.Append("<p><a class=\"b-l-btn\" style='color:gray;' >交易完成</a></p>");
                    item.BianJi = bj.ToString();
                }
                //退款成功||退款中
                else if (item.PayStatus == 6 || item.PayStatus == 5)
                {
                    var bj = new StringBuilder();
                    bj.Append("<p><a class=\"b-l-btn\" target=\"_blank\"  href=\"/UserOrder/OrderDetail?SerialNumber=" + item.SerialNumber + "\">交易详情</a></p>");
                    item.BianJi = bj.ToString();
                }
            }
            //Response.Clear();
            return Json(bList);
        }

        public ActionResult ConfirmOrder(string id)
        {
            int result = _pro.ConfirmOrder(id);
            if (result > 0)
            {
                return RedirectToAction("SecondProject");
            }
            return View();
        }
        #endregion

        #region 我关注的项目
        /// <summary>
        /// 我关注的项目
        /// </summary>
        /// <returns></returns>
        public ActionResult FocusProject()
        {
            ViewBag.MemberId = base.CurrentLoginUserId;
            return View();
        }
        [HttpPost]
        public ActionResult FocusProject(ProjectSearch search, FormCollection form)
        {
            PageView view = new PageView(form);
            // string colkey = form["colkey"];
            //string colsinfo = form["colsinfo"];
            var member = (U_Member)Session["CurrentUser"];
            search.Member = member.ID;
            PagedList<ProjectEx> bList = _pro.QueryProjectAttention(search, view);

            //Response.Clear();
            return Json(bList);

        }
        //取消关注
        [HttpPost]
        public JsonResult CancelAttention(int id)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                if (id <= 0)
                {
                    rMsg.Status = -1;
                    rMsg.Message = "参数错误！";
                }
                var member = (U_Member)Session["CurrentUser"];
                int ret = _proatt.CancelAttention(id, member.ID);
                if (ret > 0)
                {
                    //专注人数减1
                    _pro.CancelProjectExpand(id);
                    rMsg.Status = 1;
                    rMsg.Message = "操作成功！";
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {

                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }
        //判断该用户之前是否已经关注该项目
        [HttpPost]
        public JsonResult getAttention(int id, int mid)
        {
            JsonSMsg rMsg = new JsonSMsg();
            int count = _proatt.getAttention(id, mid);
            return Json(count);
        }


        #endregion

        #region 推荐的项目
        /// <summary>
        /// 推荐的项目
        /// </summary>
        /// <returns></returns>
        public ActionResult RecommendProject()
        {
            return View();
        }
        #endregion

        #region 项目时间轴

        public ActionResult ProjectDatelinetree(int pid)
        {
            if (pid == 0)
            {
                return RedirectToAction("Error", "Default", new { msg = "非法操作" });
            }
            var member = (U_Member)Session["CurrentUser"];
            if (!_pro.IsProjectOwnedUser(pid, member.ID))
            {
                return RedirectToAction("Error", "Default", new { msg = "非法操作" });
            }
            var List = _pro.QueryProjectDatelinetree(pid);



            return View(List);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public ActionResult ProjectDatelinetreeEdit(int id = 0, int pid = 0)
        {
            if (pid == 0)
            {
                return RedirectToAction("Error", "Default", new { msg = "非法操作" });
            }
            var member = (U_Member)Session["CurrentUser"];
            if (!_pro.IsProjectOwnedUser(pid, member.ID))
            {
                return RedirectToAction("Error", "Default", new { msg = "非法操作" });
            }
            var model = new R_ProjectDatelinetree
                {
                    ProjectId = pid
                };
            if (id != 0)
            {
                model = _pro.GetProjectDatelinetree(id);
            }
            return View(model);
        }
        [HttpPost]
        public ActionResult ProjectDatelinetreeEdit(R_ProjectDatelinetree model)
        {
            var rMsg = new JsonSMsg();
            try
            {
                //string errmsg = "";
                int ret = _pro.SaveProjectDatelinetree(model);
                if (ret > 0)
                {
                    rMsg.Status = 1;
                    rMsg.Data = Url.Action("ProjectDatelinetree", new { pid = model.ProjectId });
                    rMsg.Message = "操作成功！";
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }

        #endregion

        #region 删除保存的项目

        public ActionResult DeleteProject(int id)
        {
            JsonSMsg msg = new JsonSMsg();
            //删除项目
            int result = _pro.DeleteSaveProject(id);
            //删除回报
            int ret1 = _item.DeleteItemByProID(id);
            if (result > 0 && ret1 >= 0)
            {
                //return RedirectToAction("myproject", "UserProject");
                msg.Status = 1;
                msg.Message = "操作成功";
            }
            else
            {
                //return RedirectToAction("Error", "Default");
                msg.Status = -1;
                msg.Message = "操作失败";
            }
            return Json(msg);
        }

        #endregion

    }
}
